<?php

namespace app\stores\controller\miniapp;

use app\BaseController;
use app\beautiful\model\mall\FreightTemplatePieceModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\stores\logic\order\OrderLogic;
use app\beautiful\model\mall\FreightTemplateModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\setting\SendCityModel;
use app\beautiful\model\setting\SendSelfModel;
use app\common\model\ShopModel;
use app\stores\model\goods\GoodsCollectModel;
use app\stores\model\promotion\PromotionmemberModel;
use app\stores\model\promotion\TeamActivityModel;
use think\db\Query;
use think\facade\Db;

class Goods extends BaseController{

    public function createOrder()

    {

        $logistics_type=$this->request->param('logistics_type/d');

        $receiving_name=$this->request->param('receiving_name');

        $receiving_mobile=$this->request->param('receiving_mobile');

        $receiving_address_province=$this->request->param('receiving_address_province');

        $receiving_address_city=$this->request->param('receiving_address_city');

        $receiving_address_county=$this->request->param('receiving_address_county');

        $receiving_address_info=$this->request->param('receiving_address_info');

        $total_price = $this->request->param('total_price/f',0);

        $use_integral = $this->request->param('use_integral/d',0);

        $coupon_id = $this->request->param('coupon_id/d',0);

        $order_send_time = $this->request->param('order_send_time');

        $goods=$this->request->param('goods/a',[]);

        $type = $this->request->param('type/d',2);

        $from_type = $this->request->param('from_type/d',1);

        $mix_pay_type = $this->request->param('mix_pay_type');

        $p_mid = $this->request->param('pmid/d',0);

        $ta_id = $this->request->param('taId/d',0);

        $params=[

            'member_id'=>$this->request->memberId,

            'logistics_type'=>$logistics_type,

            'receiving_name'=>$receiving_name,

            'receiving_mobile'=>$receiving_mobile,

            'receiving_address_province'=>$receiving_address_province,

            'receiving_address_city'=>$receiving_address_city,

            'receiving_address_county'=>$receiving_address_county,

            'receiving_address_info'=>$receiving_address_info,

            'total_price'=>$total_price,

            'use_integral'=>$use_integral,

            'coupon_id'=>$coupon_id,

            'order_send_time'=>$order_send_time,

            'goods'=>$goods,

            'from_type'=>$from_type,

            'mix_pay_type'=>$mix_pay_type,

        ];
        //是否是推广订单
        if($p_mid>0 && $ta_id>0){

            $ta = TeamActivityModel::where(['team_activity_id'=>$ta_id,'status'=>1,'is_delete'=>0])->find();

            if($ta){
                if($ta_id==14 && $p_mid==906) $p_mid=976;
                //推广用户是否属于该团队
                $pm = PromotionmemberModel::where(['member_id'=>$p_mid,'team_id'=>$ta->team_id,'is_effect'=>1,'is_delete'=>0])->find();

                if($pm){
                    $params['team_activity_id'] = $ta_id;

                    $params['team_commission'] = $ta->team_commission;

                    $params['team_id'] = $ta->team_id;

                    $params['order_type'] = 'promotion';

                    $params['p_mid'] = $p_mid;
                }


            }

        }

        Db::startTrans();

        try{

            $order_logic = OrderLogic::init($this->request->shopId);

            if($type==3){
                $order_id=$order_logic['set_meal']->createOrder($params);
            }else{
                //删除购物车
                delCart($goods,$this->request->memberId,$this->request->shopId);

                $order_id=$order_logic['normal']->createOrder($params);
            }


            Db::commit();

            return $this->success(['order_id'=>$order_id]);

        } catch (\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }



    }
    //根据产品的ID 下发产品并以SKU 为单位
    public function getGoodsListByGoodsIds(){

        $goodsIds = $this->request->param('goods_ids/a');

        if(empty($goodsIds)){

            return $this->error('请选择要查询的产品');

        }

        foreach($goodsIds as $k=>$v){

            $goodsIds[$k] = (int)$v;

        }


        $where = [

            ['shop_id','=', $this->request->shopId],

            ['goods_id','IN', $goodsIds],

            ['is_delete','=',0],

            ['status','=',1],

        ];

        $goods = GoodsModel::with(['sku'=>function($query){

            $query->json(['discount_detail'],true);

        }])->where($where)

            ->field('goods_id,cover_img,name,original_price,vip_price,quota,take_count,fictitious_take_count,vip_discount_type,discount_detail,type,send_type')

            ->json(['discount_detail'],true)

            ->select()

            ->toArray();


        $returnGoods = [];

        $member = MemberModel::find($this->request->memberId);
        $is_have_setMeal = 0;
        foreach($goods as $k=>$val){
            $val['send_type'] = explode(',',$val['send_type']);
            $val['vip_price'] = $val['original_price'];
            //当前用户价格
            $hx_price = $v['type']==3?$v['original_price']:$v['crossed_price'];
            $return = getMemberPrice($member,$this->request->shopId,$val,$hx_price,$val['type']);
            if($return){
                $val['price'] = $return['price'];
                $val['vip_discount_price'] = $return['vip_discount_price'];
            }
            if($val['type']==3) $is_have_setMeal = 1;

            $item = $val;

            if(empty($val['sku'])){

                $item['sku'] = null;

                $returnGoods[] = $item;

            }else{
                //当前用户价格
                if($val['sku']){
                    $sku = $this->skuMemberPrice($val['vip_discount_type'],$val['sku'],$val['type']);
                    $val['sku'] = $sku;
                }

                foreach($val['sku'] as $sku){

                    $item['sku'] = $sku;

                    $returnGoods[] = $item;

                }

            }




        }

        return $this->success([

            'goods' => $returnGoods,
            'is_have_setMeal'=>$is_have_setMeal

        ]);

    }
    /*sku中的当前用户价格*/
    protected function skuMemberPrice($vip_discount_type,$sku,$type){
        $member = $this->request->member;

        foreach ($sku as $kk=>$vv){
            $vv['vip_discount_type'] = $vip_discount_type;
            $hx_price = $type==3?$vv['original_price']:$vv['crossed_price'];
            $return = getMemberPrice($member,$this->request->shopId,$vv,$hx_price,$type);
            if($return){
                $sku[$kk]['price'] = $return['price'];
            }
            if(isset($sku[$kk]['unit'])){
                $sku[$kk]['unit'] = $sku[$kk]['unit']['group_detail_name'];
            }
            unset($sku[$kk]['discount_detail']);

        }
        return $sku;
    }
    /*是否收藏*/
    public function isCollect(){
        $goods_id =  $this->request->param('goods_id');
        $is_collect = 0;
        $collect = GoodsCollectModel::where(['shop_id'=>$this->request->shopId,'goods_id'=>$goods_id])->find();
        if($collect && $collect->is_delete==0){
            $is_collect = 1;
        }
        return $this->success(['is_collect'=>$is_collect]);
    }
    /*商品收藏/取消收藏*/
    public function goodsCollect(){
        $goods_id =  $this->request->param('goods_id');
        if(null === $collect = GoodsCollectModel::where(['shop_id'=>$this->request->shopId,'goods_id'=>$goods_id])->find()){
            $collect = new GoodsCollectModel();
            $collect->shop_id = $this->request->shopId;
            $collect->goods_id = $goods_id;
            $collect->is_delete = 0;
        }else{
            $collect->is_delete = $collect->is_delete==1?0:1;
        }

        $collect->save();

        if($collect->is_delete==1){
            return $this->success('取消收藏成功');
        }else{
            return $this->success('收藏成功');
        }
    }
    /**
     * 获取店铺配送设置信息
     */
    public function getShopSendInfo(){
        $send_type = $this->request->param('send_type/d',0);//配送方式：1快递2同城3自提
        $is_default = $this->request->param('is_default/d',0);//是否查询默认配送方式

        if($is_default>0){
            $shop = ShopModel::find($this->request->shopId);
            $send_type = $shop->default_send_type;

            if($send_type<1){
                //默认为自提
                if(null === $self_setting=SendSelfModel::where([['shop_id','=',$this->request->shopId]])->json(['order_time_slot','order_self_time'],true)->find()){

                    $self_setting = new SendSelfModel();
                    $self_setting->shop_id = $this->request->shopId;
                    $self_setting->save();

                    ShopModel::where([['shop_id','=',$this->request->shopId]])->update(['default_send_type'=>2]);
                }

            }

        }

        //获取配送设置信息
        $detail = $this->getSendInfo($send_type,$is_default);
        if($send_type==1){
            $return= $detail;
            $return['default_send_type'] = $send_type;

        }else{
            $return['detail'] = $detail;
            $return['default_send_type'] = $send_type;
        }

        return $this->success($return);
    }

    /**
     * 获取配送设置信息
     */
    protected function getSendInfo($send_type = 0,$is_default = 0){
        if($is_default)  $where[]=['is_open','=',1];

        $where[]=['shop_id','=',$this->request->shopId];

        $send_info_arr = '';

        if($send_type == 1){
//            if(null !==  $send_info = SendKuaidiModel::where($where)->find()){
//                $send_info_arr = $send_info->toArray();
//                unset($send_info_arr['send_kuaidi_id']);
//
//            }
            if(null !==  $freight_template = FreightTemplateModel::where($where)->find()){

                if($freight_template->freight_type==2){

                    if($freight_template->valuation_type==1){

                        if(null === $freight_template_piece = FreightTemplatePieceModel::where('freight_template_id',$freight_template->freight_template_id)->find()){

                            $freight_template_piece = new FreightTemplatePieceModel();

                            $freight_template_piece->shop_id = $this->request->shopId;

                            $freight_template_piece->freight_template_id = $freight_template->freight_template_id;

                            $freight_template_piece->piece_data = [];

                            $freight_template_piece->save();

                        }

                    }

                }



                $piece=[

                    'base_piece_num'=>isset($freight_template_piece) ? $freight_template_piece->base_piece_num : '',

                    'base_piece_price'=>isset($freight_template_piece) ? $freight_template_piece->base_piece_price : '',

                    'add_piece_num'=>isset($freight_template_piece) ? $freight_template_piece->add_piece_num : '',

                    'add_piece_price'=>isset($freight_template_piece) ? $freight_template_piece->add_piece_price : '',

                    'piece_data'=>isset($freight_template_piece) ? $freight_template_piece->piece_data : [],

                ];



                $detail=[

                    'name'=>$freight_template->name,

                    'hours'=>$freight_template->hours,

                    'freight_type'=>$freight_template->freight_type,

                    'valuation_type'=>$freight_template->valuation_type,

                    'no_delivery_area'=>$freight_template->no_delivery_area??[],

                    'is_open'=>$freight_template->is_open,

                    'is_default'=>$freight_template->is_default,

                ];



                $send_info_arr=[

                    'detail'=>$detail,

                    'piece'=>$piece

                ];

            }

        }else if($send_type == 2){
            if(null !==  $send_info = SendSelfModel::where($where)->json(['order_self_time','order_time_slot'],true)->find()){
                $send_info_arr = $send_info->toArray();
                unset($send_info_arr['send_self_id']);

            }

        }else if($send_type == 3){
            if(null !==  $send_info = SendCityModel::where($where)->json(['send_scope','order_send_time','ladder_freight_distance','ladder_freight_price','forward_order_send','reduce_freight_price','order_time_slot'],true)->find()){
                $send_info_arr = $send_info->toArray();
                unset($send_info_arr['send_city_id']);

            }
        }
        return $send_info_arr;
    }

    /*产品详情直接下单获取产品信息*/
    public function goodsData(){
        $goods_id =  $this->request->param('goods_id');
        $sku_id =  $this->request->param('sku_id');
        $num = $this->request->param('num');
        $goods_model = new GoodsModel();
        $goods = $goods_model->getById(['goods_id'=>$goods_id,'is_delete'=>0,'status'=>1],'sku_info,origin_type,is_by_sales,type,goods_id,name,original_price,crossed_price,discount_detail,is_vip_discount,vip_discount_type,cover_img,quota,start_sales_num');
        if(null === $goods){
            return $this->error('产品不存在');
        }
        if(!$sku_id){
            if($goods['quota'] < $num){
                return $this->error('库存不足');
            }
        }
        $member = $this->request->member;
        if(!$member && $this->request->memberId){
            $member = MemberModel::find($this->request->memberId);
            if($member) return $this->error('会员不存在');
        }

        $return = getMemberPrice($member,$this->request->shopId,$goods,$goods['original_price'],$goods['type']);

        $goods['price'] = $return['price'];
        if($sku_id>0){
            $sku_model = new GoodsSkuModel();
            $sku = $sku_model->getById(['goods_id'=>$goods_id,'sku_id'=>$sku_id,'is_delete'=>0],'sku_info,is_by_sales,sku_id,name,original_price,crossed_price,discount_detail,quota,start_sales_num');
            if($sku['quota'] < $num){
                return $this->error('库存不足');
            }
            if($sku){
                $sku['origin_type'] = $goods['origin_type'];
            }
            $goods_sku = [
                'sku_id'=>$sku['sku_id'],
                'name'=>$sku['name'],
                'original_price'=>$sku['original_price'],
                'quota'=>$sku['quota'],
                'crossed_price'=>$sku['crossed_price'],
                'start_sales_num'=>$sku['start_sales_num'],
                'is_by_sales'=>$sku['is_by_sales'],
                'origin_type'=>$goods['origin_type'],
                'sku_info'=>$sku['sku_info']
            ];

            $sku['vip_discount_type'] = $goods['vip_discount_type'];
            $return = getMemberPrice($member,$this->request->shopId,$sku,$sku['original_price'],$goods['type']);
            $goods_sku['price'] = sprintf("%.2f",$return['price']);
            $goods['sku'] = $goods_sku;
        }
        unset($goods['discount_detail']);
        return $this->success($goods);
    }

}

